package com.lenovo.smarttraffic.ui.activity;

import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.google.gson.Gson;
import com.lenovo.smarttraffic.InitApp;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.api.VolleyCallBack;
import com.lenovo.smarttraffic.bean.GsonBean.SenseBean;
import com.lenovo.smarttraffic.bean.GsonBean.WeatherInfoBean;
import com.lenovo.smarttraffic.util.VolleyUtil;

import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;

public class CreateWeatherActivity extends BaseActivity {
    private SimpleDateFormat simpleDateFormat1;
    private SimpleDateFormat simpleDateFormat;
    private SimpleDateFormat simpleDateFormat3;
    private LinearLayout creativeWeatherTitleLayout;
    private TableLayout tableLayout1;
    private LineChart creativeWeatherLineChart;
    private TableLayout tableLayout2;

    private List<WeatherInfoBean.ROWSDETAILBean> weatherList;
    private boolean[] isRainy;
    private int currTemp;
    private Timer timer;
    private static final String TAG = "CreateWeatherActivity";


    @Override
    protected int getLayout() {
        return R.layout.creative_weather;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        timer = new Timer();
        simpleDateFormat1 = new SimpleDateFormat("EEEE", Locale.CHINA);
        simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA);
        simpleDateFormat3 = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        initToolBar("创意天气");
        initView();
        getWeatherData();

    }

    private void initView() {
        tableLayout1 = findViewById(R.id.tableLayout1);
        creativeWeatherLineChart = findViewById(R.id.creative_weather_LineChart);
        tableLayout2 = findViewById(R.id.tableLayout2);
        creativeWeatherTitleLayout = findViewById(R.id.creative_weather_TitleLayout);
        initChat();
    }

    Handler handler = new Handler(msg -> {
        switch (msg.what) {
            case 1:
                getSense();
                break;
        }
        return false;
    });

    private void getWeatherData() {
        VolleyUtil.post("GetWeather.do", new JSONObject(), new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                WeatherInfoBean WeatherInfoBean = new Gson().fromJson(response, WeatherInfoBean.class);
                if ("S".equals(WeatherInfoBean.getRESULT())) {
                    currTemp = WeatherInfoBean.getWCurrent();
                    weatherList = WeatherInfoBean.getROWS_DETAIL();
                    handleDate();
                    drawLineChart();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                           handler.sendEmptyMessage(1);
                        }
                    }, 0, 3000);
                }
            }

            @Override
            public void onFailure(String onError) {

            }
        });
    }

    private void getSense() {
        VolleyUtil.post("GetAllSense.do", new JSONObject(), new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                SenseBean SenseBean = new Gson().fromJson(response, SenseBean.class);
                if ("S".equals(SenseBean.getRESULT())) {
                    showBottomLayoutHeader(SenseBean);
                    showTabLayoutBottomFooter(SenseBean);
                }
            }

            @Override
            public void onFailure(String onError) {
            }
        });
    }


    private void showTabLayoutBottomFooter(SenseBean SenseBean) {
        TableRow tableRow = (TableRow) tableLayout2.getChildAt(2);
        for (int i = 0; i < tableRow.getChildCount(); i++) {
            TextView textView = (TextView) tableRow.getChildAt(i);
            switch (i) {
                case 0:
                    if (SenseBean.getLightIntensity() > 3000) {
                        textView.setText("强");
                        textView.setTextColor(Color.rgb(255, 0, 0));
                    } else if (SenseBean.getLightIntensity() >= 1000) {
                        textView.setText("中等");
                        textView.setTextColor(Color.rgb(0, 176, 80));
                    } else {
                        textView.setText("弱");
                        textView.setTextColor(Color.rgb(68, 114, 196));
                    }
                    break;
                case 1:
                    if (SenseBean.get_$Pm25270() > 150) {
                        textView.setText("重度污染");
                        textView.setTextColor(Color.rgb(153, 51, 0));
                    } else if (SenseBean.get_$Pm25270() >= 115) {
                        textView.setText("中度污染");
                        textView.setTextColor(Color.rgb(191, 144, 0));
                    } else if (SenseBean.get_$Pm25270() > 75) {
                        textView.setText("轻度污染");
                        textView.setTextColor(Color.rgb(255, 255, 64));
                    } else if (SenseBean.get_$Pm25270() >= 35) {
                        textView.setText("良");
                        textView.setTextColor(Color.rgb(146, 208, 80));
                    } else {
                        textView.setText("优");
                        textView.setTextColor(Color.rgb(68, 220, 104));
                    }
                    break;
                case 2:
                    if (SenseBean.getCo2() > 6000) {
                        textView.setText("较不宜");
                        textView.setTextColor(Color.rgb(129, 73, 172));
                    } else if (SenseBean.getCo2() >= 300) {
                        textView.setText("中");
                        textView.setTextColor(Color.rgb(255, 192, 0));
                    } else {
                        textView.setText("适宜");
                        textView.setTextColor(Color.rgb(68, 220, 104));
                    }
                    break;
                case 3:
                    if (currTemp >= 35) {
                        textView.setText("热");
                        textView.setTextColor(Color.rgb(255, 0, 0));
                    } else if (currTemp > 21) {
                        textView.setText("温暖");
                        textView.setTextColor(Color.rgb(68, 220, 104));
                    } else if (currTemp >= 12) {
                        textView.setText("舒适");
                        textView.setTextColor(Color.rgb(146, 208, 80));
                    } else {
                        textView.setText("冷");
                        textView.setTextColor(Color.rgb(52, 98, 244));
                    }
                    break;
                case 4:
                    if (SenseBean.getHumidity() >= 50) {
                        textView.setText("少发");
                        textView.setTextColor(Color.rgb(255, 255, 64));
                    } else {
                        textView.setText("较易发");
                        textView.setTextColor(Color.rgb(255, 0, 0));
                    }
                    break;
                case 5:
                    if (isRainy[0] && isRainy[1]) {
                        textView.setText("不适宜");
                        textView.setTextColor(Color.rgb(255, 0, 0));
                    } else if (!(isRainy[0] || isRainy[1] || isRainy[2])) {
                        textView.setText("适宜");
                        textView.setTextColor(Color.rgb(68, 220, 104));
                    } else {
                        textView.setText("不太适宜");
                        textView.setTextColor(Color.rgb(146, 208, 80));
                    }
                    break;
            }
        }
    }

    private void showBottomLayoutHeader(SenseBean SenseBean) {
        String[] labels = {"紫外线指数", "空气污染指数", "运动指数", "穿衣指数", "感冒指数", "洗车指数"};
        String[] values = {SenseBean.getLightIntensity() + "", SenseBean.get_$Pm25270() + "",
                SenseBean.getCo2() + "", currTemp + "", SenseBean.getHumidity() + "", ""};
        for (int i = 0; i < tableLayout2.getChildCount(); i++) {
            TableRow tableRow = (TableRow) tableLayout2.getChildAt(i);
            switch (i) {
                case 0:
                    for (int j = 0; j < tableRow.getChildCount(); j++) {
                        TextView textView = (TextView) tableRow.getChildAt(j);
                        textView.setText(labels[j]);
                    }
                    break;
                case 1:
                    for (int j = 0; j < tableRow.getChildCount(); j++) {
                        TextView textView = (TextView) ((LinearLayout) tableRow.getChildAt(j)).getChildAt(1);
                        textView.setText(values[j]);
                    }
                    break;
            }
        }
    }


    private void handleDate() {
        showTop(new Date());
        List<String> dateLabels = new ArrayList<>();
        try {
            dateLabels.add(simpleDateFormat1.format(simpleDateFormat3.parse(weatherList.get(0).getWData())));
            dateLabels.add("(今日  " + simpleDateFormat1.format(simpleDateFormat3.parse(weatherList.get(1).getWData())) + ")");
            dateLabels.add(simpleDateFormat1.format(simpleDateFormat3.parse(weatherList.get(2).getWData())));
            dateLabels.add(simpleDateFormat1.format(simpleDateFormat3.parse(weatherList.get(3).getWData())));
            dateLabels.add(simpleDateFormat1.format(simpleDateFormat3.parse(weatherList.get(4).getWData())));
            dateLabels.add(simpleDateFormat1.format(simpleDateFormat3.parse(weatherList.get(5).getWData())));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        showTableLayoutTop(dateLabels);
        //使用数组来记录有无雨水，今天、明天和后天
        isRainy = new boolean[]{false, false, false};
        TableRow tableRow1 = (TableRow) tableLayout1.getChildAt(2);
        for (int i = 1; i < 4; i++) {
            TextView textView = (TextView) tableRow1.getChildAt(i);
            if ("小雨".equals(textView.getText() + "")) {
                isRainy[i - 1] = true;
            }
        }
    }

    private void showTableLayoutTop(List<String> dateLabels) {
        for (int i = 0; i < tableLayout1.getChildCount(); i++) {
            TableRow tableRow = (TableRow) tableLayout1.getChildAt(i);
            switch (i) {
                case 0:
                    for (int j = 0; j < tableRow.getChildCount(); j++) {
                        TextView textView = (TextView) tableRow.getChildAt(j);
                        textView.setText(String.format(weatherList.get(j).getWData().substring(5, 10).replace("-", "月") + "日"));
                    }
                    break;
                case 1:
                    for (int j = 0; j < tableRow.getChildCount(); j++) {
                        TextView textView = (TextView) tableRow.getChildAt(j);
                        textView.setText(dateLabels.get(j));
                    }
                    break;
                case 2:
                    for (int j = 0; j < tableRow.getChildCount(); j++) {
                        TextView textView = (TextView) tableRow.getChildAt(j);
                        textView.setText(weatherList.get(j).getType());
                    }
                    break;
                case 3:
                    for (int j = 0; j < tableRow.getChildCount(); j++) {
                        ImageView imageView = (ImageView) tableRow.getChildAt(j);
                        if ("晴".equals(weatherList.get(j).getType())) {
                            imageView.setImageResource(R.mipmap.icon_sun);
                        } else if ("阴".equals(weatherList.get(j).getType())) {
                            imageView.setImageResource(R.mipmap.icon_yin);
                        } else if ("小雨".equals(weatherList.get(j).getType())) {
                            imageView.setImageResource(R.mipmap.icon_rain);
                        } else {
                            Log.d("WeatherActivity", weatherList.get(j).getType());
                        }
                    }
                    break;
            }

        }
    }

    private void showTop(Date date) {
        TextView titleText = (TextView) creativeWeatherTitleLayout.getChildAt(0);
        ImageView imageView = (ImageView) creativeWeatherTitleLayout.getChildAt(1);
        //%$代表占位符
        titleText.setText(String.format(Locale.CHINA, "北京\t%1$s     %2$s     %3$d度     %4$s",
                simpleDateFormat.format(date), simpleDateFormat1.format(date), currTemp, weatherList.get(1).getType()));
        if ("晴".equals(weatherList.get(1).getType())) {
            imageView.setImageResource(R.mipmap.icon_sun);
        } else if ("阴".equals(weatherList.get(1).getType())) {
            imageView.setImageResource(R.mipmap.icon_yin);
        } else if ("小雨".equals(weatherList.get(1).getType())) {
            imageView.setImageResource(R.mipmap.icon_rain);
        } else {
            Log.d("WeatherActivity", weatherList.get(1).getType());
        }
    }

    private void drawLineChart() {
        List<Entry> entries1 = new ArrayList<>();
        List<Entry> entries2 = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            String temperature = weatherList.get(i).getTemperature();
            int temp1 = Integer.parseInt(temperature.split("~")[0]);
            int temp2 = Integer.parseInt(temperature.split("~")[1]);
            entries1.add(new Entry(i, temp1));
            entries2.add(new Entry(i, temp2));
        }

        LineDataSet dataSet1 = new LineDataSet(entries1, "");
        dataSet1.setColor(Color.parseColor("#6cace8"));
        dataSet1.setDrawCircles(true);
        dataSet1.setCircleColor(Color.parseColor("#6cace8"));
        dataSet1.setCircleRadius(5);
        dataSet1.setDrawCircleHole(false);
        dataSet1.setValueFormatter((value, entry, dataSetIndex, viewPortHandler) -> value + "°");
        dataSet1.setValueTextSize(14);

        LineDataSet dataSet2 = new LineDataSet(entries2, "");
        dataSet2.setColor(Color.parseColor("#ff9800"));
        dataSet2.setDrawCircleHole(false);
        dataSet2.setCircleColor(Color.parseColor("#ff9800"));
        dataSet2.setDrawCircles(true);
        dataSet2.setValueFormatter((value, entry, dataSetIndex, viewPortHandler) -> value + "°");
        dataSet2.setValueTextSize(14);
        dataSet2.setCircleRadius(5);

        List<ILineDataSet> dataList = new ArrayList<>();
        dataList.add(dataSet1);
        dataList.add(dataSet2);

        LineData data = new LineData(dataList);
        creativeWeatherLineChart.setData(data);
        creativeWeatherLineChart.invalidate();
    }

    private void initChat() {
        XAxis xAxis = creativeWeatherLineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setLabelCount(6);
        xAxis.setEnabled(false);

        YAxis lYAxis = creativeWeatherLineChart.getAxisLeft();
        lYAxis.setAxisMinimum(10);
        lYAxis.setAxisMaximum(40);
        lYAxis.setEnabled(false);

        YAxis RYAxis = creativeWeatherLineChart.getAxisRight();
        RYAxis.setAxisMinimum(0);
        RYAxis.setEnabled(false);
        creativeWeatherLineChart.setDescription(null);
        creativeWeatherLineChart.setScaleEnabled(false);
        creativeWeatherLineChart.getLegend().setEnabled(false);
        Log.d(TAG, "initChat: ");

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.purge();
        timer.cancel();

    }
}
